package com.softlab.retailwholesalesystem.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.softlab.retailwholesalesystem.entity.OrderEntity;
import com.softlab.retailwholesalesystem.service.IOrderService;
import com.softlab.retailwholesalesystem.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/orders")
public class OrderController {
    @Autowired
    private IOrderService Service;

    @GetMapping
    public JsonResult<List<OrderEntity>> getAll(){
        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper.eq("in_out",1);
        List<OrderEntity> orderEntities = Service.list(wrapper);

        /*不该在这里出现，偷个懒*/
        for (OrderEntity o:
             orderEntities) {
            Service.setProfitAndTotalByType(o);

        }


        orderEntities = Service.list(wrapper);
        return new JsonResult<>(200,"订单列表查询成功", orderEntities);
    }

    @PostMapping
    public JsonResult<Void> addOrder(@RequestBody OrderEntity order){
        order.setInOut(1);
        Service.setProfitAndTotalByType(order);
        Service.save(order);
        return new JsonResult<>(200, "订单增加成功");
    }


    @PutMapping
    public JsonResult<Void> changeOrder(@RequestBody OrderEntity order){
        Service.setProfitAndTotalByType(order);
        Service.updateOrder(order);
        return new JsonResult<>(200, "订单修改成功");
    }

    @DeleteMapping("{id}")
    public JsonResult<Void> deleteOrder(@PathVariable Long id){
        OrderEntity order=new OrderEntity();
        order.setOrderId(id);
        order.setIsDelete(1);
        Service.updateById(order);
        return new JsonResult<>(200, "订单删除成功");
    }

    @GetMapping("/search")
    public JsonResult<List<OrderEntity>> getOrderList(OrderEntity order){
        order.setInOut(1);
        List<OrderEntity> list = Service.searchOrders(order);
        /*不该在这里出现，偷个懒*/
        for (OrderEntity o:
                list) {
            Service.setProfitAndTotalByType(o);
        }
        list = Service.searchOrders(order);
        return new JsonResult<>(200, "订单查找成功", list);
    }
}
